package com.hylanda.pb.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import java.text.ParseException;
import java.util.Map;

import net.minidev.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.hylanda.pb.service.common.ConstantHelper;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.ReadOnlyJWTClaimsSet;

/**
 * @author zhangy
 * @E-mail:blackoon88@gmail.com
 * @qq:846579287
 * @version created at：2018年1月19日 上午11:14:20 note
 */
@Service
public class PowerBiTokenService {

	public String genToken(Map<String, Object> map) {
		String wcn = (String) map.get("collectionName");
		String wid = (String) map.get("workspaceID");
		String rid = (String) map.get("reportID");
		String access_key = (String) map.get("access_key");
		String scp = (String) map.get("model");
		if (!StringUtils.isEmpty(wcn) && !StringUtils.isEmpty(wid)
				&& !StringUtils.isEmpty(rid)
				&& !StringUtils.isEmpty(access_key)
				&& !StringUtils.isEmpty(scp)) {
			JSONObject json = new JSONObject();
			// scp=Report.Read
			// scp=Report.ReadWrite
			// scp=Report.Read Workspace.Report.Create
			// scp=Report.ReadWrite Workspace.Report.Create
			// scp=Dataset.Read Workspace.Report.Create
			json.put("scp", scp);
			json.put("wcn", wcn);// 必须项
			json.put("wid", wid);// 必须项
			json.put("ver", ConstantHelper.ver);
			json.put("aud", ConstantHelper.aud);
			json.put("iss", ConstantHelper.iss);
			json.put("type", ConstantHelper.type);
			json.put("rid", rid);// reportID
			json.put("nbf", ConstantHelper.getCurrentTime());
			json.put("exp", ConstantHelper.getOneDateLaterTime());
			Payload payload = new Payload(json);
			JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
			header.setContentType("jwt");
			// Create JWS object
			JWSObject jwsObject = new JWSObject(header, payload);
			// Create HMAC signer
			JWSSigner signer = new MACSigner(access_key.getBytes());
			try {
				jwsObject.sign(signer);
			} catch (JOSEException e) {
				return null;
			}
			String token = jwsObject.serialize();
			return token;
		} else {
			return null;
		}
	}

	public boolean isValid(String apitoken) {
		Claims claims = null;
		try {
			claims=Jwts.parser().setSigningKey("valleyAuthv1.0.0").parseClaimsJws(apitoken).getBody();
		} catch (Exception e) {
			return false;
		}
		
	    //从数据库中获取token
//	    String subject=claims.getSubject();
        if(claims.getExpiration().getTime()<System.currentTimeMillis()){
        	return false;
        }
		return true;
	}
	public static void main(String[] args) {
			JSONObject json = new JSONObject();
//			json.put("appkey", "c0d1b035-d74e-bf72-3233-6439bb89a99c");
//			json.put("secret", "YTM2ZDEzNzVlMmRiNWU1MTM1MWYyYWYxMTcwYzBmNzMzMmI5MmYzZA==");
			json.put("appKey", "6430d670-859d-eb38-b723-862604cad9de");
//			System.out.println(System.currentTimeMillis()+12*3600*1000);
			json.put("exp", (System.currentTimeMillis()+12*3600*1000)/1000);
			Payload payload = new Payload(json);
			JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
//			header.setContentType("JWT");
			JOSEObjectType typ= new JOSEObjectType("JWT");
			header.setType(typ);
//			header.setCustomParameter("typ", "JWT");
//			header.setCustomParameter("secret", "YTM2ZDEzNzVlMmRiNWU1MTM1MWYyYWYxMTcwYzBmNzMzMmI5MmYzZA==");
			// Create JWS object
			JWSObject jwsObject = new JWSObject(header, payload);
			// Create HMAC signer
			JWSSigner signer = new MACSigner("NjE1ZmZkZmM5MDhjY2U0MDRmZWVmNGQ5NTdmYWZkM2Y3YWU2ZDg4OQ==");
			try {
				jwsObject.sign(signer);
			} catch (JOSEException e) {
//				return null;
			}
			String token = jwsObject.serialize();
			System.out.println(token);
			
			token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBLZXkiOiIzMWRjNTdlMS00ZTY5LWJlZGItMzc3Yy00MGEzZjQxNTQxYzUiLCJleHAiOjE1MjQ0OTI5NjN9.wSvaeXxEh67tNcCNJTf631MCUpe0EVmc7N-zA43tTZ4";
			try {
				ReadOnlyJWTClaimsSet set=JWTParser.
						parse(token).getJWTClaimsSet();//customClaims={scp=Report.Read, ver=0.2.0, wcn=platform, wid=bfe4e237-81f5-4c28-8056-e2633c647a74, type=embed, rid=c858239f-6afd-40bd-bc32-be001fec09ba}
				System.out.println(JSON.toJSON(set.getAllClaims()));
//				System.out.println(set.getCustomClaim("scp").toString());//JWTClaimsSet [iss=PowerBISDK, sub=null, aud=[https://analysis.windows.net/powerbi/api], exp=Mon Sep 11 15:46:37 CST 2017, nbf=Mon Sep 11 14:46:37 CST 2017, iat=null, jti=null, typ=null, customClaims={scp=Report.ReadWrite, ver=0.2.0, wcn=platform, wid=bfe4e237-81f5-4c28-8056-e2633c647a74, type=embed, rid=c858239f-6afd-40bd-bc32-be001fec09ba}]
			} catch (ParseException e) {
				e.printStackTrace();
			}
//			return token;
			Integer aa=128;
			int bb=128;
			if(aa==bb){
			    System.out.println("true");
			}
	}
}
